﻿using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using WcfMail;
//using BaseMailUtil;
using jmail;
//using System.Runtime.Serialization.Json;
using WcfMail.Interface;

namespace Hisuntech.SystemFramework.Net.Mail
{
    public class JMails : Emails
    {
        #region emails        
      
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="message">邮件消息</param>
        /// <returns>发送是否成功</returns>
        public override bool Send(ISysMsg message)
        {
            bool flag = false;
            Message curmsg = new Message();
            MailMessageInfo mailInfo = (MailMessageInfo)message;

            curmsg.From = mailInfo.MailFrom;
            curmsg.Subject = mailInfo.MsgSubject;
            curmsg.Charset = mailInfo.MailCharset;
            curmsg.Priority = mailInfo.IPriority;
            curmsg.Body = mailInfo.MsgContent;//发送邮件之前对内容进行压缩
            curmsg.AddRecipient(mailInfo.MailTo, "", "");
            curmsg.ISOEncodeHeaders = false;
            //curmsg.ContentType = "text/plain";
            //if (mailInfo.IsAttachment)
            //    curmsg.AddAttachment(mailInfo.AttachmentPath, true, null);

            try { 
                flag = curmsg.Send(this.SMTP_Server.MailServer, false); 
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.Message;
                flag = false; 
            }
            return flag;
        }

       
        /// <summary>
        /// 接收邮件
        /// </summary>
        /// <param name="message">邮件服务器信息</param>
        /// <param name="delMail">接收完成以后是否全部删除服务器上面的邮件</param>
        /// <param name="delMsgID">如果不全部删除，指定要删除的邮件序号（从1开始）</param>
        /// <returns>操作是否成功</returns>
        public override  bool Receive(ISysMsg message,bool delMail,int delMsgID)
        {
            jmail.POP3Class mail = new POP3Class();
            jmail.Message msg = new jmail.MessageClass();
            bool connOk = false;
            //MailMessageInfo mailInfo = (MailMessageInfo)message;
            
            try
            {
                mail.Connect(this.POP3_Server.ServerUsername,
                    this.POP3_Server.ServerPassword,
                    this.POP3_Server.MailServer,
                    this.POP3_Server.MailPort);
                connOk = true;
                //是否需要匹配邮件标题
                bool needMatching = !string.IsNullOrEmpty(this.MatchingTitle);
                for (int i = 1; i <= mail.Count; i++)
                {
                    msg = mail.Messages[i];
                    if (msg.Body != null && msg.Subject != null)//可能在某些情况下面为空
                    {
                        message.MsgSubject = "No." + i + ":" + msg.Subject; ;
                        this.Receiving(message);

                        if (!needMatching ||
                            (needMatching && msg.Subject.StartsWith(this.MatchingTitle))
                            )
                        {
                            MailMessageInfo curinof = new MailMessageInfo();
                            curinof.MessageID = i;
                            curinof.MsgSubject = msg.Subject;
                            curinof.MsgContent = msg.Body;
                            curinof.MailFrom = msg.From;

                            this.MessageQueue.Add(curinof);
                            this.Received(curinof);
                            this.CurrentMailInfo = curinof;

                            if (this.ReceiveAndDelete)
                                mail.DeleteSingleMessage(i);//在这里删除邮件会导致mail.Count改变
                        }
                    }
                    //删除当前邮件
                    if (i == delMsgID && delMsgID > 0 && !this.ReceiveAndDelete)
                        mail.DeleteSingleMessage(i);//在这里删除邮件会导致mail.Count改变
                }
                //接收邮件完毕，删除指定的邮件
                if (delMail)
                {
                    //删除所有邮件
                    mail.DeleteMessages();
                }
                

            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.Message;
                return false;
            }
            finally
            {
                if (connOk)
                    mail.Disconnect();
            }
            
           
            return true;
        }

       
        #endregion



        #region 其他

        public Dictionary<string, string> GetMail(string I_MailServer, string I_UserName, string I_UserPwd, int I_Port)
        {
            Dictionary<string, string> curD = new Dictionary<string, string>();

            jmail.POP3Class mail = new POP3Class();
            jmail.Message msg = new jmail.MessageClass();
            // msg.Charset = "utf-8";

            try { mail.Connect(I_UserName, I_UserPwd, I_MailServer, I_Port); }
            catch { return curD; }
            for (int i = 1; i <= mail.Count; i++)
            {
                msg = mail.Messages[i];
                if (msg.Body != null)
                {
                    #region 数据处理
                    if (!curD.ContainsKey(msg.Subject))
                        curD.Add(msg.Subject, msg.Body);
                    #endregion
                }
            }
            mail.Disconnect();
            return curD;
        }

        ///// <summary>
        ///// 字符转对象
        ///// </summary>
        ///// <param name="json">字符</param>
        ///// <param name="returnType">类型</param>
        ///// <returns></returns>
        //public object GetObjectFromJson(string json, Type returnType)
        //{
        //    using (System.IO.Stream stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes(json)))
        //    {
        //        var desSerializer = new DataContractJsonSerializer(returnType);
        //        var result = desSerializer.ReadObject(stream);
        //        return result;
        //    }
        //}
        
        #endregion

        #region 假邮件

        //public bool SendTxtMail(ISysMsg message)
        //{
        //    return base.WriteMail(@"D:\Companycode\IBMP\FT-Web\DllRef\" + ((MailInfos)(message)).MsgSubject, ((MailInfos)(message)).MsgContent);
        //}


        #endregion
    }
}
